package main

import (
    "io"
    "fmt"
)

type NodesSet map[string]NodeWatcher

func (ns NodesSet) check(options []string, _ []string, writer io.Writer) {
    var refresh, less bool
    for _, o := range options {
        if !refresh {
            refresh = o == "-refresh"
        }
        if !less {
            less = o == "-less"
        }
    }
    for nodeName, nd := range ns {
        if refresh {
            nd.refresh()
        }
        for _, line := range nd.Check(nodeName, less) {
            io.WriteString(writer, line+"\n")
        }
    }
}

func (ns NodesSet) status(_ []string, target []string, writer io.Writer) {
    if len(target) != 2 {
        io.WriteString(writer, "usage: status node proc\n")
        return
    }
    nodeName := target[0]
    node, ok := ns[nodeName]
    if !ok {
        io.WriteString(writer, fmt.Sprintf("node: %s not found\n", nodeName))
        return
    }
    procName := target[1]
    for _, line := range node.Status(procName) {
        io.WriteString(writer, line+"\n")
    }
}

func (ns NodesSet) run(_ []string, target []string, writer io.Writer) {
    if len(target) != 3 {
        io.WriteString(writer, "usage: run node proc command\n")
        return
    }
    nodeName := target[0]
    node, ok := ns[nodeName]
    if !ok {
        io.WriteString(writer, fmt.Sprintf("node: %s not found\n", nodeName))
        return
    }
    procName := target[1]
    commandName := target[2]
    err := node.Run(procName, commandName, writer)
    if err != nil {
        io.WriteString(writer, err.Error())
    }
}

func (ns NodesSet) commands(_ []string, target []string, writer io.Writer) {
    if len(target) != 2 {
        io.WriteString(writer, "usage: commands node proc\n")
        return
    }
    nodeName := target[0]
    node, ok := ns[nodeName]
    if !ok {
        io.WriteString(writer, fmt.Sprintf("node: %s not found\n", nodeName))
        return
    }
    procName := target[1]
    for _, l := range node.Commands(procName) {
        io.WriteString(writer, l+"\n")
    }
}

func (ns NodesSet) checkToRun(options []string, target []string, writer io.Writer) {
    io.WriteString(writer, "not implemented\n")
}
